package com.yimi.yinhepda.downLoadBaseData;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;

import com.uce.pda.util.JavaUtils;
import com.pda.ym.base.BaseActivity;
import com.uce.pda.util.Utils;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.BuildPckScanTableDao;
import com.yimi.yinhepda.db.dao.CheckScanTableDao;
import com.yimi.yinhepda.db.dao.CompanyTableDao;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.DifferScanTableDao;
import com.yimi.yinhepda.db.dao.DispactchScanMasterTableDao;
import com.yimi.yinhepda.db.dao.DispactchScanTableDao;
import com.yimi.yinhepda.db.dao.LineVoTableDao;
import com.yimi.yinhepda.db.dao.QueryQcTypeTableDao;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.SortScanTableDao;
import com.yimi.yinhepda.db.dao.StorageDetailTableDao;
import com.yimi.yinhepda.db.dao.StorageInfoTableDao;
import com.yimi.yinhepda.db.dao.SyncServerDatalTableDao;
import com.yimi.yinhepda.db.dao.UCDeptTableDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LineVoTable;
import com.yimi.yinhepda.db.table.UCDeptTable;
import com.yimi.yinhepda.entity.response.CompanyInfo;
import com.yimi.yinhepda.entity.response.CompanyResponse;
import com.yimi.yinhepda.entity.response.DeptInfoResponse;
import com.yimi.yinhepda.entity.response.LineResponse;
import com.yimi.yinhepda.entity.response.QueryQcTypeTableResponse;
import com.yimi.yinhepda.entity.response.QueryUCDeptDataResponse;
import com.yimi.yinhepda.entity.response.StorageDetail;
import com.yimi.yinhepda.entity.response.StorageDetailResponse;
import com.yimi.yinhepda.entity.response.StorageInfo;
import com.yimi.yinhepda.entity.response.StorageInfoResponse;
import com.yimi.yinhepda.entity.response.SyncServerData;
import com.yimi.yinhepda.entity.response.SyncServerDataResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.ActivityStack;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LoadUtils;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author 000432
 */

public class DownLoadBaseData extends UICallBack {

    private Context context;
    private SharedPreferUtil sharedPreferUtil = SharedPreferUtil.getInstance();
    /**
     * 据分页大小
     */
    private int mPageSize = 1000;
    private int startIndex = 1;
    private String mLastTime;
    private SyncServerData mSyncServerData;
    private List<SyncServerData> syncServerDataList;
    private boolean isShowDialog;
    private int mUcCurrentpage;
    private int mUcPageSize = 1000;

    public DownLoadBaseData(Context context, boolean isShowDialog) {
        this.context = context;
        this.isShowDialog = isShowDialog;
    }

    @Override
    public void onError(final String msg) {
        if (isShowDialog) {
            LoadUtils.hideLoading(context);
            ((BaseActivity) context).showToast(msg);
        }
        LogUtil.e(msg);
    }

    @Override
    public void syncParseNetworkResponse(Object obj) {
        LogUtil.e("startIndex=" + startIndex);

        if (obj instanceof DeptInfoResponse) {
            //网点
            DeptInfoResponse response = (DeptInfoResponse) obj;
            if (response.getData() != null) {
               final List<DeptInfoResponse.DataBean> list = response.getData().getRecords();
                if (list != null && !list.isEmpty()) {
                    LogUtil.e("网点数=" + list.size());
                    LogUtil.e("网点总数=" + (list.size() * startIndex));
                    try {
                        Utils.getThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                //添加新数据
                                new DepartmentTableDao().createOrUpdate(DepartmentTable.parse(list));
                            }
                        });
                    } catch (Exception e) {
                        LogUtil.e(e.toString());
                    }
                }
            }
        } else if (obj instanceof LineResponse) {
            //线路
            LineResponse response = (LineResponse) obj;
            if (response.getData() != null) {
                final List<LineVoTable> list = response.getData().getRecords();
                if (list != null && !list.isEmpty()) {
                    LogUtil.e("线路数=" + list.size());
                    LogUtil.e("线路总数=" + (list.size() * startIndex));
                    try {
                        Utils.getThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                new LineVoTableDao().createOrUpdate(list);
                            }
                        });
                    } catch (Exception e) {
                        LogUtil.e(e.toString());
                    }
                }
            }
        } else if (obj instanceof CompanyResponse) {
            //账套
            CompanyResponse response = (CompanyResponse) obj;
            if (response.getData() != null) {
                final List<CompanyInfo> list = response.getData().getRecords();
                if (list != null && !list.isEmpty()) {
                    LogUtil.e("账套数=" + list.size());
                    LogUtil.e("账套总数=" + (list.size() * startIndex));
                    Utils.getThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            new CompanyTableDao().createOrUpdate(list);
                        }
                    });
                }
            }
        } else if (obj instanceof QueryUCDeptDataResponse) {
            //优速网点数据
            QueryUCDeptDataResponse response = (QueryUCDeptDataResponse) obj;
            if (response.getData() != null) {
                final List<UCDeptTable> list = response.getData().getRecords();
                if (list != null && !list.isEmpty()) {
                    LogUtil.e("优速网点数=" + list.size() + " * " + mUcCurrentpage);
                    LogUtil.e("优速网点总数=" + response.getData().getTotalRecord() + "+总页=" + response.getData().getTotalPage());
                    //每次删除优速快递网点，重新下载
                    final UCDeptTableDao unDeptDao = new UCDeptTableDao();
                    unDeptDao.deleteAll();
                    Utils.getThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            unDeptDao.createOrUpdate(list);
                        }
                    });

                }
            }
        }
    }

    @Override
    public void onSuccess(final Object obj) {

        if (obj instanceof DeptInfoResponse) {
            //网点
            //根据同步表判断该表需要同步
            DeptInfoResponse response = (DeptInfoResponse) obj;
            if (response.isSuccess() && response.getData() != null) {
                //判断是否还有数据
                if ((startIndex * mPageSize) < response.getData().getTotalSize()) {
                    startIndex++;
                    updateDataMethod(mLastTime, DeptInfoResponse.class, mSyncServerData);
                    return;
                }
            }

            LogUtil.e("网点下载结束--->" + DateHelper.getDateTimeFormate(new Date()));

            LogUtil.e("线路下载开始--->" + DateHelper.getDateTimeFormate(new Date()));

            startIndex = 1;

            //线路下载
            String lastTime = getLastTime(LineVoTableDao.class);
            lastTime = DateHelper.getTargetDateByDays(lastTime, -1);
            SyncServerData syncServerData = getServerDataTask(Constants.TABLE_NAME_LINE);
            updateDataMethod(lastTime, LineResponse.class, syncServerData);
        } else if (obj instanceof LineResponse) {
            //线路
            LineResponse response = (LineResponse) obj;
            if (response.isSuccess() && response.getData() != null) {
                if ((startIndex * mPageSize) < response.getData().getTotalSize()) {
                    startIndex++;
                    updateDataMethod(mLastTime, LineResponse.class, mSyncServerData);
                    return;
                }
            }
            startIndex = 1;

            LogUtil.e("线路下载结束--->" + DateHelper.getDateTimeFormate(new Date()));

            LogUtil.e("下载账套开始--->" + DateHelper.getDateTimeFormate(new Date()));

            //下载账套
            String lastTime = getLastTime(CompanyTableDao.class);
            SyncServerData syncServerData = getServerDataTask(Constants.BASE_SYS_COMPANY);
            updateDataMethod(lastTime, CompanyResponse.class, syncServerData);
        } else if (obj instanceof CompanyResponse) {
            //账套
            CompanyResponse response = (CompanyResponse) obj;
            if (response.isSuccess() && response.getData() != null) {
                if ((startIndex * mPageSize) < response.getData().getTotalSize()) {
                    startIndex++;
                    updateDataMethod(mLastTime, CompanyResponse.class, mSyncServerData);
                    return;
                }
            }
            startIndex = 1;

            LogUtil.e("下载账套结束--->" + DateHelper.getDateTimeFormate(new Date()));
            LogUtil.e("下载优速网点开始--->" + DateHelper.getDateTimeFormate(new Date()));
            mUcCurrentpage = 1;
            getUCDeptData(mUcCurrentpage);
        } else if (obj instanceof QueryUCDeptDataResponse) {
            //下载优速网点数据
            QueryUCDeptDataResponse response = (QueryUCDeptDataResponse) obj;
            if (response.isSuccess() && response.getData() != null) {
                if (mUcCurrentpage <= response.getData().getTotalPage()) {
                    mUcCurrentpage++;
                    getUCDeptData(mUcCurrentpage);
                    return;
                }
            }
            LogUtil.e("下载优速网点结束--->" + DateHelper.getDateTimeFormate(new Date()));
            sharedPreferUtil.setServerIpHaveChanged(false);
            LoadUtils.hideLoading(context);
            if (isShowDialog) {
                //继续下载快递寄出数据
                JavaUtils.downloadData("FULL_DATA", isShowDialog, context);
//                LoadUtil.showSuccess("下载完成", context);
            }
        } else if (obj == null) {
            if (isShowDialog) {
                if (((Activity) context).isFinishing()) {
                    return;
                }
                LoadUtils.hideLoading(context);
                MyDialog dialog = MyDialog.getInstance(context);
                dialog.setIcon(R.mipmap.alert_error);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("系统提示");
                dialog.setMessage("基础数据下载失败，是否重试？");
                dialog.setPositiveClickListener("重试", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        MyDialog.setNull();
                        String lastTime = getLastTime(DepartmentTableDao.class);
                        SyncServerData syncServerData = getServerDataTask(Constants.TABLE_NAME_DEPT);
                        updateDataMethod(lastTime, DeptInfoResponse.class, syncServerData);
                    }
                });
                if (sharedPreferUtil.getServerIpHaveChanged()) {
                    dialog.setNegativeClickListener(R.drawable.btn_login_selector, "退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ActivityStack.getInstance().exit();
                        }
                    });
                    dialog.setCancelable(false);
                    dialog.setCanceledOnTouchOutside(false);
                } else {
                    dialog.setNegativeClickListener(R.drawable.btn_login_selector, "继续使用", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            MyDialog.setNull();
                        }
                    });
                }

                try {
                    dialog.show();
                } catch (Exception e) {
                    LogUtil.e(e.toString());
                }
            }
        }
    }

    /**
     * 根据基础数据同步表，下载基础数据
     *
     * @param lastTime      表对应的最后更新时间
     * @param responseClazz 响应实体
     */
    private void updateDataMethod(String lastTime, Class<?> responseClazz, SyncServerData syncServerData) {
        int mStatus = 0;
        if (syncServerData != null) {
            mStatus = syncServerData.getSTATUS();
        }

        if (mStatus != 1) {
            //状态不为1时，该表无需同步更新，直接检测下一张表是否需要同步更新
            if (responseClazz == DeptInfoResponse.class) {
                //线路下载
                lastTime = getLastTime(LineVoTableDao.class);
                syncServerData = getServerDataTask(Constants.TABLE_NAME_LINE);
                updateDataMethod(lastTime, LineResponse.class, syncServerData);
            } else if (responseClazz == LineResponse.class) {
                //下载库存
                lastTime = getLastTime(StorageInfoTableDao.class);
                syncServerData = getServerDataTask(Constants.WMS_STORAGE);
                updateDataMethod(lastTime, StorageInfoResponse.class, syncServerData);
            } else if (responseClazz == StorageInfoResponse.class) {
                //下载库存明细
                lastTime = getLastTime(StorageDetailTableDao.class);
                syncServerData = getServerDataTask(Constants.WMS_STORAGE_DETAIL);
                updateDataMethod(lastTime, StorageDetailResponse.class, syncServerData);
            } else if (responseClazz == StorageDetailResponse.class) {
                //下载账套
                lastTime = getLastTime(CompanyTableDao.class);
                syncServerData = getServerDataTask(Constants.BASE_SYS_COMPANY);
                updateDataMethod(lastTime, CompanyResponse.class, syncServerData);
            } else if (responseClazz == CompanyResponse.class) {
                //下载问题件
                lastTime = getLastTime(QueryQcTypeTableDao.class);
                syncServerData = getServerDataTask(Constants.BASE_BDM_QC_TYPE);
                updateDataMethod(lastTime, QueryQcTypeTableResponse.class, syncServerData);
            } else if (responseClazz == QueryQcTypeTableResponse.class) {
                sharedPreferUtil.setServerIpHaveChanged(false);
                if (isShowDialog) {
                    LoadUtils.hideLoading(context);
                }
            }
            return;
        }

        if (lastTime == null) {
            lastTime = Common.DATA_LAST_TIME;
        }
        mLastTime = lastTime;
        mPageSize = syncServerData.getPAGE_SIZE();
        mSyncServerData = syncServerData;

        if (isShowDialog) {
            showPgDlgByTableName(syncServerData.getTABLE_NAME());
        }

        Map<String, String> params = new HashMap<>(5);
        params.put("tableName", syncServerData.getTABLE_NAME());
        params.put("pageSize", mPageSize + "");
        params.put("startIndex", startIndex + "");
        params.put("lastTime", mLastTime);
        params.put("cdstatus", syncServerData.getCdstatus());
        params.put("fromType", syncServerData.getFROM_TYPE() + "");

        String url = Constants.SERVER_IP + "app" + syncServerData.getSYNC_SERVICE_URL() + "?appKey=5cd97ddcbba444b4b5287f031d977567";

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(responseClazz)
                .setUrl(url)
                .setParams(params)
                .isDataBaseDownload(true)
                .execute(this);

    }

    public void showPgDlgByTableName(final String tableName) {
        switch (tableName) {
            case Constants.TABLE_NAME_DEPT:
                LoadUtils.showLoading("正在下载网点信息...", context);
                break;
            case Constants.WMS_STORAGE:
                LoadUtils.showLoading("正在下载库区信息...", context);
                break;
            case Constants.WMS_STORAGE_DETAIL:
                LoadUtils.showLoading("正在下载库区详细信息...", context);
                break;
            case Constants.TABLE_NAME_LINE:
                LoadUtils.showLoading("正在下载线路信息...", context);
                break;
            case Constants.BASE_SYS_COMPANY:
                LoadUtils.showLoading("正在下载账套信息...", context);
                break;
            case Constants.BASE_BDM_QC_TYPE:
                LoadUtils.showLoading("正在下载问题件类型信息...", context);
                break;
            default:
                break;
        }
    }

    /**
     * 基础资料下载 网点 库区 线路 问题 账套
     */
    public void downloadBaseData() {
        if (isShowDialog) {
            LoadUtils.showLoading("基础数据同步中...", context);
        }
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                if (sharedPreferUtil.getServerIpHaveChanged()) {
                    /***删除所有基础数据***/
                    new DepartmentTableDao().deleteAll();
                    new LineVoTableDao().deleteAll();
                    new StorageInfoTableDao().deleteAll();
                    new StorageDetailTableDao().deleteAll();
                    new CompanyTableDao().deleteAll();
                    new QueryQcTypeTableDao().deleteAll();
                    /***删除其他表所有数据***/
                    new BuildPckScanTableDao().deleteAll();
                    new CheckScanTableDao().deleteAll();
                    new DifferScanTableDao().deleteAll();
                    new DispactchScanTableDao().deleteAll();
                    new SortScanTableDao().deleteAll();
                    new UnloadScanTableDao().deleteAll();
                    new UnloadTaskTableDao().deleteAll();
                    new ScanDetailVoDao().deleteAll();
                    new DispactchScanMasterTableDao().deleteAll();
                    new BuildPckScanTableDao().deleteAll();
                    /****删除基础数据同步表数据****/
                    new SyncServerDatalTableDao().deleteAll();
                }
                //每次删除优速快递网点，重新下载
                new UCDeptTableDao().deleteAll();

                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                /****基础数据同步****/
                syncServerData();
            }

            @Override
            public void onError(Throwable throwable) {
                if (isShowDialog) {
                    LoadUtils.hideLoading(context);
                }
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 基础数据同步
     */
    private void syncServerData() {
        Map<String, String> params = new HashMap<>();
        params.put("tableName", "sync_server_data_task");
        params.put("startIndex", "1");
        params.put("fromType", "3");
        params.put("lastTime", Common.DATA_LAST_TIME);
        params.put("cdstatus", "all");
        params.put("pageSize", "500");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(SyncServerDataResponse.class)
                .setUrl(Constants.SYNC_SERVER_DATA_URL)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e("基础数据同步失败：" + msg);
                        if (isShowDialog) {
                            LoadUtils.hideLoading(context);
                            /****基础数据同步失败时，重新尝试对话框****/
                            retrySyncServerDataDialog(msg);
                        }
                    }

                    @Override
                    public void onSuccess(final Object obj) {
                        if (isShowDialog) {
                            SyncServerDataResponse response = (SyncServerDataResponse) obj;
                            if (response != null && response.isSuccess() && response.getData() != null) {
                                syncServerDataList = response.getData().getRecords();
                                /****下载基础数据****/
                                downLoadDataBase();
                            } else {
                                /****基础数据同步失败时，重新尝试对话框****/
                                retrySyncServerDataDialog(null);
                            }
                        } else {
                            SyncServerDataResponse response = (SyncServerDataResponse) obj;
                            if (response != null && response.isSuccess() && response.getData() != null) {
                                syncServerDataList = response.getData().getRecords();
                                /****下载基础数据****/
                                downLoadDataBase();
                            }
                        }

                    }
                });
    }

    /**
     * 基础数据同步失败时，重新尝试对话框
     */
    private void retrySyncServerDataDialog(String msg) {
        MyDialog dialog = new MyDialog(context);
        dialog.setIcon(R.mipmap.alert_error);
        if (msg == null) {
            dialog.setMessage("基础数据同步失败，是否重试？");
        } else {
            dialog.setMessage(msg);
        }
        dialog.setPositiveClickListener("重试", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                syncServerData();
            }
        });
        if (sharedPreferUtil.getServerIpHaveChanged()) {
            dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ActivityStack.getInstance().exit();
                }
            });
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
        } else {
            dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "继续使用", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }

        dialog.show();
    }

    /**
     * 下载基础数据
     */
    private void downLoadDataBase() {
        LogUtil.e("网点下载开始--->" + DateHelper.getDateTimeFormate(new Date()));
        //下载网点
        String lastTime = getLastTime(DepartmentTableDao.class);
        SyncServerData syncServerData = getServerDataTask(Constants.TABLE_NAME_DEPT);
        updateDataMethod(lastTime, DeptInfoResponse.class, syncServerData);
    }

    private SyncServerData getServerDataTask(String tableName) {
        if (syncServerDataList != null) {
            for (SyncServerData entity : syncServerDataList) {
                if (tableName.equals(entity.getTABLE_NAME()) && entity.getSTATUS() == 1) {
                    return entity;
                }
            }
        }
        return null;
    }

    /**
     * 查询数据库中lasttime最大值
     */
    public String getLastTime(Object obj) {
        String lastTime;
        //判断是否是第一次下载
        if (sharedPreferUtil.getServerIpHaveChanged()) {
            lastTime = Common.DATA_LAST_TIME;
        } else {
            //查询数据库中lasttime最大值
            if (obj == DepartmentTableDao.class) {
                //获取网点lasttime
                lastTime = new DepartmentTableDao().findOrderByLatestTime2();
            } else if (obj == LineVoTableDao.class) {
                //获取线路lasttime
                lastTime = new LineVoTableDao().findOrderByLatestTime2();
            } else if (obj == StorageInfoTableDao.class) {
                //获取库存lasttime
                lastTime = new StorageInfoTableDao().findOrderByLatestTime2();
            } else if (obj == StorageDetailTableDao.class) {
                //库存明细lasttime
                lastTime = new StorageDetailTableDao().findOrderByLatestTime2();
            } else if (obj == CompanyTableDao.class) {
                //获取账套lasttime
                lastTime = new CompanyTableDao().findOrderByLatestTime();
            } else if (obj == QueryQcTypeTableDao.class) {
                //获取问题件lasttime
                lastTime = new QueryQcTypeTableDao().findOrderByLatestTime();
            } else {
                lastTime = Common.DATA_LAST_TIME;
            }
        }
        if (lastTime != null) {
            lastTime = lastTime.replace("T", " ").replace("Z", "");
        }
        return lastTime;
    }

    private void getUCDeptData(int currentpage) {
        if (isShowDialog) {
            LoadUtils.showLoading("正在下载快递网点信息...", context);
        }
        Map<String, String> params = new HashMap<>(2);
        params.put("currentPage", String.format("%s", currentpage));
        params.put("pageSize", String.format("%s", mUcPageSize));

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryUCDeptDataResponse.class)
                .setUrl(Constants.URL_QUERY_UC_DEPT_DATA)
                .setParams(params)
                .execute(this);
    }
}
